<template>
    <view class="apply-pages" v-if="isLoad">
        <!-- <back></back> -->
        <view class="apply-form pl-lg pr-lg">
            <!-- <view class="flex justify-between align-center padding-tb-30">
				<view class="text-bold">收货地址</view>
				<view class="flex align-center" @tap.stop="form.status = form.status ==1 ? 0 : 1">
					<image src="../../../static/index/yuan.png" mode="" class="defimg" v-if="form.status ==0"></image>
					<image src="../../../static/index/def.png" mode="" class="defimg" v-if="form.status ==1"></image>
					<view class="text-26 margin-left-10">设为默认地址</view>
				</view>
			</view>
			<view class="bg-ff padding-30 radius-10 flex align-center margin-bottom-20">
				<view class="text-28">联系人</view>
				<input v-model="form.user_name" type="text" class="text-28 flex-1 text-right" maxlength="20"
					:placeholder="rule[0].errorMsg" />
			</view>
			<view class="bg-ff padding-30 radius-10 flex align-center margin-bottom-20">
				<view class="text-28">手机号</view>
				<input v-model="form.mobile" type="text" class="text-28 flex-1 text-right"
					:placeholder="rule[1].errorMsg" />
			</view> -->
            <view class="fill-base mt-md radius-16">
                <view class="flex-between ml-lg mr-lg b-1px-b">
                    <view class="item-text">联系人</view>
                    <input
                        v-model="form.user_name"
                        type="text"
                        class="item-input flex-1 text-right"
                        maxlength="20"
                        :placeholder="rule[0].errorMsg"
                    />
                </view>
                <view class="flex-between ml-lg mr-lg">
                    <view class="item-text">手机号</view>
                    <input
                        v-model="form.mobile"
                        type="text"
                        class="item-input flex-1 text-right"
                        :placeholder="rule[1].errorMsg"
                    />
                </view>
            </view>
            <view class="fill-base mt-md radius-16" style="position: relative">
                <!-- <view class="flex-between ml-lg mr-lg b-1px-b">
					<view class="item-text">选择地区</view>
					<view @tap.stop="toChooseLocation" class="item-input text flex-1">
						<view class="flex-y-center text-right">
							<view class="flex-1 text-right">{{form.address || `点击右边图标设置`}}</view><i
								class="iconfont iconjuli ml-sm" :style="{color: primaryColor}"></i>
						</view>
					</view>
				</view> -->
                <view
                    class="flex-between ml-lg mr-lg b-1px-b"
                    style="padding: 30rpx 0"
                    @click="is_area_show = true"
                >
                    <view class="item-text">选择地区</view>
                    <view class="">{{ form.address ? form.address : "请选择选择地区" }}</view>
                </view>
                <view
                    class="flex-between ml-lg mr-lg b-1px-b padding-tb-30"
                    @click="is_street_show = true"
                >
                    <view class="item-text">选择街道</view>
                    <view class="">{{ streetanme ? streetanme : "请选择街道" }}</view>
                </view>
                <view
                    class="flex-between ml-lg mr-lg b-1px-b padding-tb-30"
                    @click="is_community_show = true"
                >
                    <view class="item-text">选择小区</view>
                    <view class="">{{ communityname ? communityname : "请选择小区" }}</view>
                </view>
                <view class="search-box" v-if="is_s_show">
                    <view
                        class="padding-30"
                        v-for="(item, index) in searchlist"
                        :key="index"
                        @click="chosexq(item.name)"
                    >
                        {{ item.name }}
                    </view>
                </view>
            </view>
            <view class="fill-base mt-md radius-16">
                <view class="flex-between ml-lg mr-lg">
                    <view class="item-text flex-1" style="width: 300rpx">设为默认地址</view>
                    <!-- status 1默认； -->
                    <view @tap.stop="form.status = form.status == 1 ? 0 : 1" class="item-input">
                        <i
                            class="iconfont icon-switch"
                            :class="[{ 'icon-switch-on': form.status == 1 }]"
                            :style="{ color: form.status == 1 ? '#007aff' : '#f2f2f2' }"
                        ></i>
                    </view>
                </view>
            </view>
            <view class="f-icontext c-caption mt-md"> 设置后，下单时优先展示该地址</view>
        </view>

        <view class="space-max-footer"></view>

        <fix-bottom-button
            @cancel="toDel"
            @confirm="submit"
            :text="textArr"
            bgColor="#fff"
        ></fix-bottom-button>
        <view class="layer" v-if="is_area_show" @click="is_area_show = false">
            <view class="layer-content" @click.stop>
                <view
                    class="confirm-bar line-height-80 padding-lr-30 bg-ff border-bottom-ed flex align-center justify-between"
                >
                    <view class="text-cc" @click="is_area_show = false">取消</view>
                    <view class="" style="color: #007aff" @click="adresSubmit()">确定</view>
                </view>
                <picker-view
                    :value="multiIndex"
                    :indicator-style="indicatorStyle"
                    class="picker-view"
                    @change="changeAdres"
                >
                    <picker-view-column>
                        <view
                            class="item-pircker"
                            v-for="(item, index) in arealist1"
                            :key="index"
                            >{{ item.label }}</view
                        >
                    </picker-view-column>
                    <picker-view-column v-if="arealist2">
                        <view
                            class="item-pircker"
                            v-for="(item, index) in arealist2"
                            :key="index"
                            >{{ item.label }}</view
                        >
                    </picker-view-column>
                    <picker-view-column v-if="arealist3">
                        <view
                            class="item-pircker"
                            v-for="(item, index) in arealist3"
                            :key="index"
                            >{{ item.label }}</view
                        >
                    </picker-view-column>
                </picker-view>
            </view>
        </view>
        <!-- 所属街道 -->
        <view class="layer flex align-end" v-if="is_street_show" @click="is_street_show = false">
            <view class="layerbg" @click.stop>
                <view class="position-relative padding-top-40 flex align-center">
                    <view class="text-28 text-center flex-one">请选择街道</view>
                    <view class="context" @click="choseStreet()">确认</view>
                </view>
                <view class="padding-lr-20 padding-tb-15 bg-ff radius-10 margin-top-20">
                    <view class="padding-20 flex align-center radius-10 bg-f5 margin-lr-30">
                        <image
                            src="../../../static/wImg/greySea.png"
                            mode=""
                            class="searchimg"
                        ></image>
                        <view class="searchline"></view>
                        <input
                            type="text"
                            placeholder="输入您想要的内容"
                            class="text-24 flex-one"
                            v-model="keyword"
                            @confirm="searchStreet"
                        />
                    </view>
                    <picker-view
                        :value="streetiIndex"
                        :indicator-style="indicatorStyle"
                        class="picker-view1"
                        @change="changeStreet"
                    >
                        <picker-view-column>
                            <view
                                class="item-pircker"
                                v-for="(item, index) in streetlist"
                                :key="index"
                                >{{ item.name }}
                            </view>
                        </picker-view-column>
                    </picker-view>
                </view>
            </view>
        </view>
        <!-- 所属小区 -->
        <view
            class="layer flex align-end"
            v-if="is_community_show"
            @click="is_community_show = false"
        >
            <view class="layerbg" @click.stop>
                <view class="position-relative padding-top-40 flex align-center">
                    <view class="text-28 text-center flex-one">请选择小区</view>
                    <view class="context" @click="choseCommunity()">确认</view>
                </view>
                <view class="padding-lr-20 padding-tb-15 bg-ff radius-10 margin-top-20">
                    <view class="padding-20 flex align-center radius-10 bg-f5 margin-lr-30">
                        <image
                            src="../../../static/wImg/greySea.png"
                            mode=""
                            class="searchimg"
                        ></image>
                        <view class="searchline"></view>
                        <input
                            type="text"
                            placeholder="输入您想要的内容"
                            class="text-24 flex-one"
                            v-model="keyword"
                            @confirm="searchCommunity"
                        />
                    </view>
                    <picker-view
                        :value="comiIndex"
                        :indicator-style="indicatorStyle"
                        class="picker-view1"
                        @change="changeCommunity"
                    >
                        <picker-view-column>
                            <view
                                class="item-pircker"
                                v-for="(item, index) in communitylist"
                                :key="index"
                                >{{ item.name }}
                            </view>
                        </picker-view-column>
                    </picker-view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import areaData from "../components/w-picker/areadata/areadata.js";
import { mapState, mapMutations } from "vuex";
export default {
    components: {
        areaData,
    },
    data() {
        return {
            isLoad: false,
            options: {},
            textArr: [
                {
                    text: "删除",
                    type: "cancel",
                },
                {
                    text: "保存",
                    type: "confirm",
                },
            ],
            form: {
                id: 0,
                user_name: "",
                mobile: "",
                address: "",
                address_info: "",
                lng: "",
                lat: "",
                status: 0,
                street_id: "",
                community_id: "",
                community_name: "",
                street_name: "",
            },
            rule: [
                {
                    name: "user_name",
                    checkType: "isNotNull",
                    errorMsg: "输入联系人姓名",
                    regType: 2,
                },
                {
                    name: "mobile",
                    checkType: "isMobile",
                    errorMsg: "输入手机号",
                },
                {
                    name: "address",
                    checkType: "isNotNull",
                    errorMsg: "设置地区",
                },
            ],
            lockTap: false,
            arealist1: [],
            arealist2: [],
            arealist3: [],
            is_area_show: false,
            multiIndex: [0, 0, 0],
            areaname: "",
            multiArray: [],
            indicatorStyle: "height: 80rpx;",
            searchlist: [],
            is_s_show: false,
            streetlist: [],
            streetanme: "",
            streetiIndex: [0],
            comiIndex: [0],
            indicatorStyle: "height: 60rpx;",
            is_street_show: false,
            keyword: "",
            streetid: "",
            is_community_show: false,
            communitylist: [],
            communityname: "",
            communityid: "",
        };
    },
    computed: mapState({
        primaryColor: (state) => state.config.configInfo.primaryColor,
        subColor: (state) => state.config.configInfo.subColor,
        location: (state) => state.user.location,
    }),
    onLoad(options) {
        this.options = options;
        this.initIndex();
    },
    onReady() {
        console.log(areaData);
        this.arealist1 = areaData;
        this.arealist2 = areaData[0].children;
        this.arealist3 = areaData[0].children[0].children;
    },
    methods: {
        ...mapMutations(["updateUserItem", "updateOrderItem"]),
        async initIndex() {
            // #ifdef H5
            if (this.$jweixin.isWechat()) {
                await this.$jweixin.initJssdk();
                this.$jweixin.wxReady(() => {
                    this.$jweixin.hideOptionMenu();
                });
            }
            // #endif
            let { id = 0 } = this.options;
            uni.setNavigationBarTitle({
                title: id ? `编辑地址` : `添加新地址`,
            });
            if (!id) {
                this.textArr.splice(0, 1);
                this.isLoad = true;
                this.$util.setNavigationBarColor({
                    bg: this.primaryColor,
                });
                return;
            }
            let data = await this.$api.mine.addressInfo({
                id,
            });
            this.streetanme = data.street_name;
            this.communityname = data.community_name;
            for (let key in this.form) {
                this.form[key] = data[key];
            }
            this.$util.setNavigationBarColor({
                bg: this.primaryColor,
            });
            this.isLoad = true;
        },
        // 选择地区
        async toChooseLocation(e) {
            await this.$util.checkAuth({
                type: "userLocation",
            });
            let { lat: locaLat = "", lng: locaLng = "" } = this.location;
            let { id = 0, lat: addrLat, lng: addrLng } = this.form;

            if (id) {
                locaLat = addrLat;
                locaLng = addrLng;
            }

            let param = {};
            if (!locaLat && !locaLng) {
                // #ifdef H5
                if (this.$jweixin.isWechat()) {
                    this.$util.showLoading();
                    await this.$jweixin.wxReady2();
                    let { latitude, longitude } = await this.$jweixin.getWxLocation();
                    locaLat = latitude;
                    locaLng = longitude;
                }
                // #endif
                // #ifdef APP-PLUS
                let location = await this.$util.getBmapLocation();
                locaLat = location.lat;
                locaLng = location.lng;
                // #endif
            }

            // #ifndef MP-WEIXIN
            param = {
                latitude: locaLat,
                longitude: locaLng,
            };
            // #endif
            let [, { address = "", longitude, latitude, name }] = await uni.chooseLocation(param);
            if (!address) return;
            this.form.address = address;
            this.form.lng = longitude;
            this.form.lat = latitude;
        },
        async toDel() {
            let [res_del, { confirm }] = await uni.showModal({
                title: "提示",
                content: "请确认是否要删除此数据?",
            });
            if (!confirm) return;
            let { id } = this.form;
            let { check_id } = this.$util.getPage(-1);
            if (this.lockTap) return;
            this.lockTap = true;

            this.$util.showLoading();
            try {
                await this.$api.mine.addressDel({
                    id,
                });
                this.$util.hideAll();
                this.$util.showToast({
                    title: `删除成功`,
                });
                this.lockTap = false;
                if (id == check_id) {
                    this.updateOrderItem({
                        key: "haveOperItem",
                        val: true,
                    });
                }
                setTimeout(() => {
                    this.$util.back();
                    this.$util.goUrl({
                        url: 1,
                        openType: `navigateBack`,
                    });
                }, 1000);
            } catch (e) {
                setTimeout(() => {
                    this.lockTap = false;
                    this.$util.hideAll();
                }, 2000);
            }
        },
        //表单验证
        validate(param) {
            let validate = new this.$util.Validate();
            this.rule.map((item) => {
                let { name } = item;
                validate.add(param[name], item);
            });
            let message = validate.start();
            return message;
        },
        async submit() {
            let param = this.$util.deepCopy(this.form);
            let msg = this.validate(param);
            if (msg) {
                this.$util.showToast({
                    title: msg,
                });
                return;
            }
            if (this.lockTap) return;
            this.lockTap = true;

            this.$util.showLoading();
            try {
                let methodModel = param.id ? `addressUpdate` : `addressAdd`;
                await this.$api.mine[methodModel](param);
                this.$util.hideAll();
                this.$util.showToast({
                    title: `保存成功`,
                });
                setTimeout(() => {
                    this.$util.back();
                    this.$util.goUrl({
                        url: 1,
                        openType: `navigateBack`,
                    });
                }, 1000);
            } catch (e) {
                setTimeout(() => {
                    this.lockTap = false;
                    this.$util.hideAll();
                }, 2000);
            }
        },
        changeAdres(e) {
            let curMultiIndex = e.detail.value;
            if (curMultiIndex[0] != this.multiIndex[0]) {
                this.multiIndex = [curMultiIndex[0], 0, 0];
            } else if (curMultiIndex[1] != this.multiIndex[1]) {
                this.multiIndex = [this.multiIndex[0], curMultiIndex[1], 0];
            } else if (curMultiIndex[2] != this.multiIndex[2]) {
                this.multiIndex = [this.multiIndex[0], this.multiIndex[1], curMultiIndex[2]];
            }
            console.log(this.multiIndex);
            var i = this.multiIndex[0];
            var j = this.multiIndex[1];
            var k = this.multiIndex[2];
            this.arealist2 = this.arealist1[i].children;
            this.arealist3 = this.arealist1[i].children[j].children;
            console.log(this.cateid);
        },
        adresSubmit() {
            var i = this.multiIndex[0];
            var j = this.multiIndex[1];
            var k = this.multiIndex[2];
            this.form.address =
                this.arealist1[i].label +
                "/" +
                this.arealist1[i].children[j].label +
                "/" +
                this.arealist1[i].children[j].children[k].label;
            this.is_area_show = false;
            this.getStreet();
        },
        getSearch(e) {
            uni.request({
                url: "https://same.ascetic.top/index.php?i=666&m=longbing_massages_city&s=massage/app/Index/getCommunity&urls=massage/app/Index/getCommunity",
                header: {
                    autograph: uni.getStorageSync("autograph"),
                },
                data: {
                    name: this.form.address_info,
                    area: this.form.address,
                },
                success: (res) => {
                    this.searchlist = res.data.data;
                    if (this.searchlist.length) {
                        this.is_s_show = true;
                    }
                },
            });
        },
        chosexq(name) {
            this.form.address_info = name;
            this.is_s_show = false;
        },
        //街道列表
        async getStreet() {
            let res = await this.$api.service.getStreet({
                area: this.form.address,
                keyword: this.keyword,
            });
            console.log(res, "街道列表");
            this.streetlist = res;
        },
        // 小区列表
        async getCommunity() {
            let res = await this.$api.service.getCommunity({
                area: this.form.address,
                street_id: this.form.street_id,
            });
            console.log(res, "小区列表");
            this.communitylist = res;
        },
        changeStreet(e) {
            let curMultiIndex = e.detail.value;
            if (curMultiIndex[0] != this.streetiIndex[0]) {
                this.streetiIndex = [curMultiIndex[0]];
            }
            console.log(this.streetiIndex);
        },
        changeCommunity(e) {
            let curMultiIndex = e.detail.value;
            if (curMultiIndex[0] != this.comiIndex[0]) {
                this.comiIndex = [curMultiIndex[0]];
            }
            console.log(this.comiIndex);
        },
        choseStreet() {
            var i = this.streetiIndex[0];
            this.streetanme = this.streetlist[i].name;
            this.form.street_name = this.streetlist[i].name;
            this.form.street_id = this.streetlist[i].id;
            console.log(this.streetanme, this.form.street_id);
            this.keyword = "";
            this.getCommunity();
            this.is_street_show = false;
        },
        choseCommunity() {
            var i = this.comiIndex[0];
            this.communityname = this.communitylist[i].name;
            this.form.community_name = this.communitylist[i].name;
            this.form.community_id = this.communitylist[i].id;
            console.log(this.communityname, this.form.community_id);
            this.keyword = "";
            this.is_community_show = false;
        },
        searchStreet() {
            this.getStreet();
        },
    },
};
</script>

<style lang="scss">
@import url(@/components/common.css);

.layer {
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
}

.layer-content {
}

/* 浮层内容 */
.confirm-bar {
    position: fixed;
    bottom: 600rpx;
    left: 0;
    width: 750rpx;
}

.line-height-80 {
    height: 80rpx;
    line-height: 80rpx;
}

.padding-lr-30 {
    padding-left: 30rpx;
    padding-right: 30rpx;
}

.bg-ff {
    background: #fff;
}

.border-bottom-ed {
    border-bottom: 1rpx solid #ededed;
}

.flex {
    display: flex;
}

.align-center {
    align-items: center;
}

.justify-between {
    justify-content: space-between;
}

.picker-view {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 750rpx;
    height: 600rpx;
    background: #fff;
}

.item-pircker {
    line-height: 80rpx;
    height: 80rpx;
    align-items: center;
    justify-content: center;
    text-align: center;
}

.scimg {
    width: 45rpx;
    height: 45rpx;
    position: absolute;
    top: -20rpx;
    right: -20rpx;
}

.search-box {
    width: 75%;
    height: 500rpx;
    background: #fff;
    border: 1rpx solid #ededed;
    position: absolute;
    bottom: -500rpx;
    right: 0;
    overflow-y: scroll;
}

.padding-30 {
    padding: 30rpx;
}

.defimg {
    width: 40rpx;
    height: 40rpx;
}

.layerbg {
    width: 750rpx;
    height: 516rpx;
    background: #ffffff;
    border-radius: 20rpx 20rpx 0rpx 0rpx;
}

.context {
    font-size: 28rpx;
    color: #606dce;
    right: 30rpx;
    position: absolute;
}

.searchimg {
    width: 25rpx;
    height: 23rpx;
}

.searchline {
    width: 2rpx;
    height: 32rpx;
    background: #b0b0b0;
    margin: 0 20rpx;
}

.van-img {
    width: 100%;
    height: 100%;
}

.picker-view1 {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 750rpx;
    height: 300rpx;
    background: #fff;
}

.item-pircker {
    line-height: 60rpx;
    height: 60rpx;
    align-items: center;
    justify-content: center;
    text-align: center;
}
</style>
